#!/usr/bin/env node

const Router = require('koa-router'),
  commodity = require('../models/commodity_mod'),
  // jwt = require('jsonwebtoken'),
  // {JWT_KEY} = require('../lib/constant.js'),
  // _ = require('lodash'),
  router = new Router,
  image = require('../models/image_mod'),
  sj = require('silly-datetime');
router.prefix('/api/commodity');


router.get('/', async (ctx, next) => {
  // let {email,password} = ctx.request.body;
  let res = await commodity.Commodity_gets();

  ctx.body = res;
})
router.delete('/',async (ctx,next)=>{
  let {business_id,business_password,commodity_id,admin_id,admin_password} = ctx.request.body;
  let res = await commodity.Commodity_delete(business_id,business_password,commodity_id,admin_id,admin_password);

  ctx.body = res;
})
router.delete('/temp',async(ctx,next)=>{
  let {commodity_temp_id,business_id,business_password} = ctx.request.body;
  let res = await commodity.Commodity_temp_delete(business_id,business_password,commodity_temp_id);
  ctx.body = res;
})

router.post('/', async (ctx, next) => {
  let time = sj.format(new Date());
  let filename = '';
if(ctx.request.body.File == undefined){
  const file = ctx.request.files.File;
  filename = await image.Image(file);
}else{
  let fileurl = ctx.request.body.File.split('/')
  filename = fileurl[fileurl.length-1]
}
  let { business_id, commodity_temp_title, commodity_temp_descript, commodity_temp_money, commodity_temp_t,commodity_temp_addres } = ctx.request.body;
  let res = await commodity.Commodity_temp(business_id, commodity_temp_title,filename, commodity_temp_descript, commodity_temp_money,commodity_temp_t,commodity_temp_addres,time);

  ctx.body = res;
})

router.get('/commodity_temp', async (ctx, next) => {
  let res = await commodity.Commodity_temp_get();
  ctx.body = res;
})
router.post('/commodity', async (ctx, next) => {
  let { commodity_temp_id } = ctx.request.body;
  let res = await commodity.Commodity(commodity_temp_id);
  ctx.body = res;
})
router.post('/commodity_defate',async(ctx,next)=>{
  let {commodity_temp_id} = ctx.request.body;
  let res = await commodity.Commodity_defate(commodity_temp_id);
  ctx.body = res;
})
router.post('/commodity_temp',async(ctx,next)=>{
  let {business_id} = ctx.request.body;
  let res = await commodity.Commodity_temp_get_one(business_id);
  ctx.body = res;
})

module.exports = router;
